package com.zhz.company.controller;

import com.zhz.common.tool.excel.utils.ExcelExportUtil;
import com.zhz.common.tool.mybatisplus.base.core.contract.Page;
import com.zhz.common.tool.mybatisplus.base.core.contract.PageParam;
import com.zhz.common.tool.mybatisplus.base.core.contract.R;
import com.zhz.common.utils.ConvertUtils;
import com.zhz.company.contract.excel.UserExcel;
import com.zhz.company.excel.UserExcelExport;
import com.zhz.company.repository.service.UserDemoService;
import com.zhz.model.demo.contract.dto.UserDemoDTO;
import com.zhz.model.demo.contract.param.UserDemoQueryParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhouhengzhe
 * @date 2023/4/6
 */
@Api(value="demo",tags = "demo")
@RestController
@RequestMapping("/user")
public class UserDemoController {

    @Autowired
    private UserDemoService userDemoService;

    @Autowired
    private ExcelExportUtil excelExportUtil;

    @Autowired
    private UserExcelExport userExcelExport;

    @ApiOperation("导出excel,已测，1万数据大约30s")
    @PostMapping("/exportExcel")
    public R<Void> exportExcel(@RequestBody UserDemoQueryParam userDemoQueryParam){
        PageParam<UserDemoQueryParam> pageParam=new PageParam<>();
        pageParam.setLimit(userDemoQueryParam.getLimit());
        pageParam.setPage(userDemoQueryParam.getPage());
        pageParam.setParam(userDemoQueryParam);
        Page<UserDemoDTO> page = userDemoService.page(pageParam);

        if (CollectionUtils.isNotEmpty(page.getList())){
            List<UserExcel> userExcels = page.getList().stream().map(i -> {
                return ConvertUtils.sourceToTarget(i, UserExcel.class);
            }).collect(Collectors.toList());
            long start = System.currentTimeMillis();
            //前端传过来的title
            String title = "用户列表";
            HSSFWorkbook wb = excelExportUtil.exportExcel(userExcels, title);
            excelExportUtil.createExcelFile(wb, "/Users/zhouhengzhe/Documents/tempExcel/" + "/userdemo.xls");
            System.out.println(System.currentTimeMillis() - start);
        }
        return R.ok();
    }
    @ApiOperation("大数据导出")
    @PostMapping("/exportExcelBigData")
    public void exportExcelBigData(@RequestBody UserDemoQueryParam userDemoQueryParam, HttpServletResponse response){
        userExcelExport.exportWithBigData("用户列表1", userDemoQueryParam,response);
    }
}
